// Copyright 2007 Helsinki Institute for Information Technology
// and the authors.
//
// Authors: Harri Hämäläinen <harri.hamalainen@helsinki.fi>
//          Toni Ruottu <toni.ruottu@iki.fi>

// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

//Views
function GenericView(collection) {
    var feed_connector = new FeedConnector(collection);
    

    // This is called when EntryEditor's submit button is clicked
    GenericView.checkEditorFields = function(collection) {
        if ($('post_title').value == '' || $('post_author').value == '') {
            alert('At least title and author must be nonempty');
            return false;
        }
        var feed_connector = new FeedConnector($('collection_id').value);
        var enclosure_type_ = document.getElementsByName('enclosure_type');
        var enclosure_file_;
        
        if (enclosure_type_[0].checked) {// adding new enclosure
            enclosure_type_ = 'add_new';
            enclosure_file_ = $('new_enclosure_filename').value;
        } else if (enclosure_type_[1].checked) { // adding existing enclosure
            enclosure_type_ = 'add_existing';
            enclosure_file_ = $('existing_enclosure_filename').value;
        }
        var postObject = {
            id: $('id').value,
            title: $('post_title').value,
            published: $('publish_date').value, 
            author: $('post_author').value,
            content: $('post_content').value, 
            entry_key: $('entry_key').value, 
            enclosure_type: enclosure_type_,
            enclosure_file: enclosure_file_
        };
        if (feed_connector.postEntry(postObject)) {
            return true;
        }
        return false;
    }

    this.postComment = function(entry_id, nick,tags,msg) {
        feed_connector.postComment(entry_id, nick, tags, msg);
    }
    this.postEntry = function(title, author, content, entry_key, enclosure_type, enclosure_filename) {
        feed_connector.postEntry(title, author, content, entry_key, enclosure_type, enclosure_filename);
    }
    this.updateTags = function(entry_id) {
        return Util.escape(feed_connector.getPopularTags(entry_id));
    }
    this.getFeedTitle = function() {
        return '<div id="feed_header" align="center"><a href="'
                +'/collection/'+collection+'/web/index.html'
                +'">'+feed_connector.getFeedTitle()+'</a></div>';
    }

    this.getAuthor = function(obj) {
        try {
            return obj.author.name.escapeHTML();
        } catch(e) {
            return "";
        }
    }

    this.getContent = function(obj) {
        try {
            return obj.content.escapeHTML();
        } catch (e) {
            return "";
        }
    }

    this.getEnclosure = function(obj) {
        try {
            return obj.link[0].href.escapeHTML();
        } catch (e) {
            return "";
        }
    }
    this.getEntryID = function(obj) {
        try {
            return obj.id.escapeHTML();
        } catch (e) {
            return "";
        }
    }
    this.getPublishDate = function(obj) {
        try {
            return obj.published.escapeHTML();
        } catch (e) {
            return "";
        } 
    }
    this.getFancyPublishDate = function(obj) {
        try {
            return Util.getUTCFriendlyDate(obj.published).escapeHTML();
        } catch (e) {
            return "";
        } 
    }
    
    this.getTitle = function(obj) {
        try {
            return obj.title.escapeHTML();
        } catch(e) {
            return "";
        }
    }

    this.getEnclo = function(enclo_values,open) {
        var encloTemplate;
        if(open)
        {
        encloTemplate = new Template(
            '<div id="enclosure#{enclosure_number}"><table class="bar"><tr><td id="expand#{enclosure_number}" /><img src="/static/icons/down.png" alt="v" /></td><td class="filename"><a id="enclosure_link#{enclosure_number}" href="#{enclosure_url}">#{enclosure_name}</a></td></tr></table>'
            +'<div id="content#{enclosure_number}" class="entry_enclosures"><object data="#{enclosure_url}">Your browser lacks support for this kind of media files.</object></div></div>'
        );
        }
        else
        {
        encloTemplate = new Template(
            '<div id="enclosure#{enclosure_number}"><table class="bar"><tr><td><img id="expand#{enclosure_number}" src="/static/icons/right.png" alt=">" /></td><td class="filename"><a id="enclosure_link#{enclosure_number}" href="#{enclosure_url}">#{enclosure_name}</a></td></tr></table></div>'
        );
        }
        return encloTemplate.evaluate(enclo_values);
    }

    this.getEntries = function() {
        var entries = feed_connector.getEntries();
        var entryTemplate = new Template(
            '<hr />'
            +'<div class="entry">'
            +'<div class="entry_title"><a href="?entry=#{entry_id}">#{title}</a></div>'
            +'<div class="entry_author">#{published} #{author}</div>'
            +'<div id="entry_tags">#{tags}</div>'
            +'<div class="entry_content">#{content}</div>'
            +'#{enclo}'
            +'<div class="entry_comments"><a href="?entry=#{entry_id}">#{comment_count} comments</a></div>'
            +'</div>'
        );

        var inner = "";
        var entry;
        var e = 0;
        for (var i = entries.length-1; i >= 0; i -= 1) {
            try {
                entry = entries[i][1].evalJSON(true);
                if (entry == '()')
                    continue;
            } catch (e) {
                continue;
            }
            var entry_values = {
                entry_id: entries[i][0], 
                title: this.getTitle(entry),
                published: Util.getUTCFriendlyDate(this.getPublishDate(entry)),
                author: this.getAuthor(entry),
                tags: Util.escape(feed_connector.getPopularTags(entries[i][0])),
                content: this.getContent(entry),
                comment_count: feed_connector.getCommentCount(entries[i][0])
            };
            if  (this.getEnclosure(entry) != '') {
                var enclo_values = {
                    enclosure_url: this.getEnclosure(entry),
                    enclosure_name: this.getEnclosure(entry).split('/').pop(),
                    enclosure_number: e++
                };
                entry_values['enclo'] = this.getEnclo(enclo_values, false);
                /*
                entry_values['enclo'] = this.getEnclo(enclo_values, true);
                */
            }
            inner += entryTemplate.evaluate(entry_values);
        }

        return inner;
    }
    
    this.getEntry = function(entry_id) {
        var entry = feed_connector.getEntry(entry_id);
        var entry_template = new Template(
            '<div class="entry">'
            +'<div class="entry_title">#{title}</div>'
            +'<div class="entry_author">#{published} #{author}</div>'
            +'<div id="entry_tags">#{tags}</div>'
            +'<div class="entry_content">#{content}</div>'
            +'<div class="entry_enclosures"><a href="#{enclosure_url}">#{enclosure}</a></div>'
            +'</div>'
        );
        var entry_values = {
            title: this.getTitle(entry),
            published: Util.getUTCFriendlyDate(this.getPublishDate(entry)),
            author: this.getAuthor(entry),
            tags: Util.escape(feed_connector.getPopularTags(entry_id)),
            content: this.getContent(entry)
        };
        if  (this.getEnclosure(entry) != '') {
                entry_values['enclosure'] = 'Enclosure',
                entry_values['enclosure_url'] = this.getEnclosure(entry)
        }
        return entry_template.evaluate(entry_values);
    }

    this.getComments = function(entry_id) {
        var inner = '<div id="entry_comments"><hr /><h3>Comments</h3>';
        var comments = feed_connector.getComments(entry_id);
        var comments_template = new Template(
            '<div class="comment_header">#{published} #{author} wrote:</div>'
            +'<blockquote class="comment_content">#{content}</blockquote>'
        )
        for (var i = 0; i<comments.length; i += 1) {
            var comment_values = {
                published: this.getFancyPublishDate(comments[i]),
                author: this.getAuthor(comments[i]),
                content: this.getContent(comments[i])
            }
            inner += comments_template.evaluate(comment_values);
        }
        inner += '</div>';
        return inner;
    }

    this.getCommentForm = function(entry_path) {
        var comment_template = new Template(
            '<hr /><h3>Add Comment</h3><center>'
            + '<form id="add_comment" action=""><table><tr><td>Your nickname:</td>'
            + '<td><input id="comment_nickname" type="text" name="comment_nickname" value="#{author}" /></td></tr>'
            + '<tr><td>Tags:</td><td><input id="comment_tags" type="text" name="comment_tags" value="#{mytags}"/></td></tr>'
            + '<tr><td colspan="2">Message:<br />'
            + '<textarea id="comment_content" name="comment_content">'
            + '</textarea></td></tr></table>'
            + '<input type="button" id="comment_submit" value="Send" />'
            + '</form></center>'
        );
        var comment_values = {}
        comment_values['mytags'] = feed_connector.getMyTags(entry_path);
        comment_values['author'] = feed_connector.getRealName();
        return comment_template.evaluate(comment_values);
    }
    
    this.getEditorForm = function(entry_key) {
        if (entry_key != null) {
            var entry = feed_connector.getEntry(entry_key);
        } else {
            entry_key = "";
        }
        var action_url = '/collection/'+collection;
            action_url += '?next=/collection/' + collection + '/web/index.html';
        
        var editor_template = new Template(
            '<hr /><center><h3>New Post</h3>'
            +'<form id="upload_form" action="#{form_action}" method="post" enctype="multipart/form-data"'
            +'onsubmit="return GenericView.checkEditorFields()">'
            +'<input type="hidden" id="id" value="#{entry_id}" />'
            +'<input type="hidden" id="publish_date" value="#{publish_date}" />'
            +'<input type="hidden" id="collection_id" value="#{collection}" />'
            +'<input type="hidden" id="entry_key" value="#{entry_key}" />'
            +'<table><tr><td>Topic</td><td><input type="text" id="post_title" value="#{title}"/></td></tr>'
            +'<tr><td>Author</td><td><input type="text" id="post_author" value="#{author}" /></td></tr>'
            +'<tr><td>Content</td><td><textarea id="post_content">#{content}</textarea></td></tr>'
            +'<tr><td>Enclosure</td><td>'
            +'<input type="radio" name="enclosure_type" value="add_new" />Import new'
            +'<input type="file" id="new_enclosure_filename" name="put_file_under_name:file" /></td></tr>'
            +'<tr><td></td><td><input type="radio" name="enclosure_type" value="add_existing" #{old_checked} />'
            +'Link to URL'
            +'<input type="text" id="existing_enclosure_filename" value="#{url}" /></td></tr>'
            +'<tr><td></td><td><input type="radio" name="enclosure_type" value="nothing" #{nothing_checked} />'
            +'No enclosure</td></tr>'
            +'<tr><td><input type="submit" id="new_post" value="Post" /></td><td></td></tr></table></form></center>'
        );
        var editor_values = {
            form_action: action_url,
            collection: collection,
            entry_key: entry_key.split('/', 2)[0],
            author: feed_connector.getRealName()
        }
        editor_values['entry_id'] =  entry_key ? this.getEntryID(entry) : '';
        editor_values['publish_date'] = entry_key ? this.getPublishDate(entry) : '';
        editor_values['title'] = entry_key ? this.getTitle(entry) : '';
        editor_values['content'] = entry_key ? this.getContent(entry) : '';
        editor_values['url'] = entry_key ? this.getEnclosure(entry) : '';
        editor_values['old_checked'] = this.getEnclosure(entry) != '' ? 'checked' : '';
        editor_values['nothing_checked'] = this.getEnclosure(entry) == '' ? 'checked' : '';

        return editor_template.evaluate(editor_values);
    }

    this.getOptions = function(entry_path) {
        var inner = '<hr /><i>'
        inner += '<a href="?configure">Configure Blog</a> <a href="?new_post">New Post</a> ';
        if (entry_path != null) {
            inner += '<a href="?edit_post='+entry_path+'">Edit post</a> '
                + '<a href="?remove_post='+entry_path+'"' 
                + 'onClick="return confirm(\'Are you sure you want to delete this post?\');">'
                + 'Remove post</a>';

        }
        inner += '</i><a href="/feed/'+collection+'">'
              + '<img src="/static/icons/feed-icon-14x14.png" alt=""/> Get Feed</a>';
        return inner;
    }
}

var FeedView = {

    init: function(element, collection) {
        getEnclo2 = function(enclo_values,open) {
            var encloTemplate;
            if(open)
            {
            encloTemplate = new Template(
                '<table class="bar"><tr><td id="expand#{enclosure_number}" /><img src="/static/icons/down.png" alt="v" /></td><td class="filename"><a id="enclosure_link#{enclosure_number}" href="#{enclosure_url}">#{enclosure_name}</a></td></tr></table>'
                +'<div id="content#{enclosure_number}" class="entry_enclosures"><object data="#{enclosure_url}">Your browser lacks support for this kind of media files.</object></div>'
            );
            }
            else
            {
            encloTemplate = new Template(
                '<table class="bar"><tr><td><img id="expand#{enclosure_number}" src="/static/icons/right.png" alt=">" /></td><td class="filename"><a id="enclosure_link#{enclosure_number}" href="#{enclosure_url}">#{enclosure_name}</a></td></tr></table>'
            );
            }
            return encloTemplate.evaluate(enclo_values);
        }
        this.expander = function(e) {
            expand = function() {
                var enclo_values = {
                    enclosure_url: $('enclosure_link' + e).getAttribute('href'),
                    enclosure_name: $('enclosure_link' + e).textContent,
                    enclosure_number: e
                };
                if( $('content' + e))
                {
                    html = getEnclo2(enclo_values,false);
                    //alert('kiinni (' + $('content' + e) + ')');
                }
                else
                {
                    html = getEnclo2(enclo_values,true);
                    //alert('auki');
                }

                $('enclosure' + e).innerHTML = html
                //alert($('enclosure' + e).innerHTML);
                //$('expand' + e).onclick = expand;

            }
            return expand;
        }

        var generic_view = new GenericView(collection);
        element.innerHTML = generic_view.getFeedTitle();
        element.innerHTML += generic_view.getEntries();
        element.innerHTML += generic_view.getOptions();
        var e = 0;
            
        while ($('expand' + e))
        {
            $('expand' + e).onclick = this.expander(e);
            e++;
        }
    }
}

var EntryView = {
    init: function(element, collection, entry_path) {
        var self = this;
        var generic_view = new GenericView(collection);
        element.innerHTML = generic_view.getFeedTitle();
        element.innerHTML += generic_view.getEntry(entry_path);
        element.innerHTML += generic_view.getCommentForm(entry_path);
        element.innerHTML += generic_view.getComments(entry_path);
        element.innerHTML += generic_view.getOptions(entry_path);
        
        this.onMessageEntered = function(){
            var nick = $('comment_nickname').value;
            var msg = $('comment_content').value;
            var tags = $('comment_tags').value;
            if (nick==''){
                alert("Nickname cannot be empty");
                return;
            }
            $('comment_content').value = '';
            generic_view.postComment(entry_path, nick,tags,msg);   
            $('entry_tags').innerHTML = generic_view.updateTags(entry_path);
            $('entry_comments').innerHTML = generic_view.getComments(entry_path);
        }
 
        $('comment_submit').onclick = function() {   
            self.onMessageEntered();
        };


    }
}

var EntryEditor = {
    init: function(element, collection, entry_path) {
        var generic_view = new GenericView(collection);
        element.innerHTML = generic_view.getFeedTitle();
        element.innerHTML += generic_view.getEditorForm(entry_path);
        element.innerHTML += generic_view.getOptions(entry_path);
    }
}

var ConfigView = {
    title: '',
    ask_title: function ()  {
        var new_title = prompt('Enter a new title: ', this.title);
        if (new_title) { 
            HttpConnector.doPut('../info/title', new_title);
        }
        location.reload();
    },
    init: function(element, collection) {
        var generic_view = new GenericView(collection);
        var feed_connector = new FeedConnector(collection);
        this.feed_title2 = feed_connector.getFeedTitle();
        var myHTML = generic_view.getFeedTitle();
        myHTML += '<h3>Get your own blog</h3><a href="index.html?new_blog" id="create_new">Create new</a><br />';
        myHTML += '<h3>Configure this</h3><a href="#" id="feed_title">Change title ('+this.feed_title2+')</a><br />';
        var groups = Util.getRightedGroups('/friend/post/feed');
        for (var i = 0; i < groups.length; i += 1) {
            var group = groups[i];
            var url = '/collection/' + group;
            var title = HttpConnector.doGet(url + '/info/title?output=text&timeout=0') || group;

            var id = 'group' + i;
            var html = 'Posting and editing of entries is enabled for friends of '
                + '<a id="' + id + '" href="'+url+'/web/index.html'+'">'+title+'</a>. ';
            myHTML += html;
        }
        if (groups.length > 0) {
            var dhtml = '<a href="#" id="disableeditors">Disable</a>';
            myHTML += dhtml;
   
        } else {
            var ehtml = 'Posting and editing of entries is disabled for friends. <a href="#" id="enableeditors">Enable</a>';
            myHTML += ehtml;

        }
        
        var cgroups = Util.getRightedGroups('/0x/post/feed/tags');
        if (cgroups.length > 0) {
            var disable_everyone_html = '<br />Posting tags and comments for entries is enabled for everybody '
                    +'<a href="#" id="disablecomments">Disable</a>';
            myHTML += disable_everyone_html;

        } else {
            var enable_everyone_html = '<br />Posting tags and comments for entries is disabled for others.  <a href="#" id="enablecomments">Enable</a>';
            myHTML += enable_everyone_html;

        }
        element.innerHTML = myHTML;
        $('feed_title').onclick = function() {
            var new_title = prompt('Enter a new title: ', this.title);
                if (new_title) { 
                    HttpConnector.doPut('../info/title', new_title);
                }
            location.reload();
        };
        if ($('disableeditors'))
        $('disableeditors').onclick = function() {
            Util.disableRights('/friend/post/feed');
            Util.disableRights('/friend/put/file');
            location.reload();
        };
        if ($('enableeditors'))
        $('enableeditors').onclick = function() {
            Util.enableRights('/post/feed');
            Util.enableRights('/put/file');
            location.reload();
        };
        if ($('enablecomments'))
        $('enablecomments').onclick = function() {
            Util.enableRights('/post/feed/tags', collection, '0x')
            Util.enableRights('/post/feed/comments', collection, '0x')
            location.reload();
        };
        if ($('disablecomments'))
        $('disablecomments').onclick = function() {
             Util.disableRights('/0x/post/feed/tags')
             Util.disableRights('/0x/post/feed/comments')
             location.reload();
        };

    }  
};

function get_params() {
    var result = {};
    var q = location.search;
    if (q.length > 1) {
        q = q.substring(1, q.length);
        var fields = q.split('&');
        for (var i = 0; i < fields.length; i += 1) {
            var parts = fields[i].split('=');
            var key = parts[0];
            var value = parts[1];
            result[key] = decodeURIComponent(value);
        }
    }
    return result;
}

onload = function() {
    collection = (location.href.match(/collections?\/(\w*)\//))[1];
    //     $("documenthead").innerHTML += "<link rel=\"alternate\" type=\"application/atom+xml\" title=\"Atom\" href=\"/feed/"+collection+"\" />";
    var q = get_params();
    var main_element = $('view');

    if (q.entry) {
        entry_key =  location.href.match(/web\/index.html\?entry=(.+)/)[1];
        new EntryView.init(main_element, collection, entry_key);
    } else if (q.new_post) {
        new EntryEditor.init(main_element, collection);            
    } else if (q.edit_post) {
        entry_key = location.href.match(/web\/index.html\?edit_post=(.+)/)[1];
        new EntryEditor.init(main_element, collection, entry_key);
    } else if (q.remove_post) { 
        entry_key = location.href.match(/web\/index.html\?remove_post=(.*)/)[1];
        var feed_connector = new FeedConnector(collection);
        feed_connector.removePost(entry_key);
        setTimeout("", 1000);
        location = '/collection/'+collection+'/web/index.html';
    } else if (q.configure) {
        new ConfigView.init(main_element, collection);
    } else if (q.new_blog) {
        var html = HttpConnector.doGet('index.html');
        var css = HttpConnector.doGet('blog.css');
        location = '/?create_collection=true'
        + '&put:info/title='
        + '&put:info/type=tag:hiit.fi,2007-07:blog'
        + '&put:web/index.html=' + encodeURIComponent(html)
        + '&put:web/blog.css=' + encodeURIComponent(css);
    } else {
        new FeedView.init(main_element, collection);
    }
}
